<template>
  <div class="report-container">
    <el-tabs v-model="activeTab" type="card">
      <!-- 收支项明细 -->
      <el-tab-pane label="收支项明细" name="incomeExpense">
        <div class="tab-content">
          <!-- 搜索区域 -->
          <el-card class="search-card">
            <el-form :model="searchForm1" inline>
              <el-form-item label="类型">
                <el-select v-model="searchForm1.type" placeholder="请选择类型" clearable>
                  <el-option label="收入" value="income" />
                  <el-option label="支出" value="expense" />
                </el-select>
              </el-form-item>
              <el-form-item label="日期范围">
                <el-date-picker
                  v-model="searchForm1.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch1">搜索</el-button>
                <el-button @click="handleReset1">重置</el-button>
                <el-button @click="handleExport1">导出</el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 统计信息 -->
          <el-card class="stats-card">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value income">{{ totalIncome }}</div>
                  <div class="stat-label">总收入</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value expense">{{ totalExpense }}</div>
                  <div class="stat-label">总支出</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value profit">{{ netProfit }}</div>
                  <div class="stat-label">净利润</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value">{{ recordCount }}</div>
                  <div class="stat-label">记录数</div>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <!-- 数据表格 -->
          <el-card class="table-card">
            <el-table :data="tableData1" v-loading="loading1">
              <el-table-column prop="date" label="日期" width="120" />
              <el-table-column prop="type" label="类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.type === 'income' ? 'success' : 'danger'">
                    {{ row.type === 'income' ? '收入' : '支出' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="category" label="分类" width="120" />
              <el-table-column prop="amount" label="金额" width="120">
                <template #default="{ row }">
                  <span :class="row.type === 'income' ? 'income' : 'expense'">
                    ¥{{ row.amount }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="remark" label="备注" />
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="pagination1.current"
                v-model:page-size="pagination1.size"
                :page-sizes="[10, 20, 50, 100]"
                :total="pagination1.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange1"
                @current-change="handleCurrentChange1"
              />
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <!-- 收付款明细 -->
      <el-tab-pane label="收付款明细" name="paymentReceipt">
        <div class="tab-content">
          <!-- 搜索区域 -->
          <el-card class="search-card">
            <el-form :model="searchForm2" inline>
              <el-form-item label="类型">
                <el-select v-model="searchForm2.type" placeholder="请选择类型" clearable>
                  <el-option label="收款" value="receipt" />
                  <el-option label="付款" value="payment" />
                </el-select>
              </el-form-item>
              <el-form-item label="客户/供应商">
                <el-input v-model="searchForm2.customerSupplier" placeholder="请输入客户或供应商名称" clearable />
              </el-form-item>
              <el-form-item label="日期范围">
                <el-date-picker
                  v-model="searchForm2.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch2">搜索</el-button>
                <el-button @click="handleReset2">重置</el-button>
                <el-button @click="handleExport2">导出</el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 统计信息 -->
          <el-card class="stats-card">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value income">{{ totalReceipt }}</div>
                  <div class="stat-label">总收款</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value expense">{{ totalPayment }}</div>
                  <div class="stat-label">总付款</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value profit">{{ netCashFlow }}</div>
                  <div class="stat-label">净现金流</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value">{{ recordCount2 }}</div>
                  <div class="stat-label">记录数</div>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <!-- 数据表格 -->
          <el-card class="table-card">
            <el-table :data="tableData2" v-loading="loading2">
              <el-table-column prop="date" label="日期" width="120" />
              <el-table-column prop="type" label="类型" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.type === 'receipt' ? 'success' : 'danger'">
                    {{ row.type === 'receipt' ? '收款' : '付款' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="customerSupplier" label="客户/供应商" width="150" />
              <el-table-column prop="amount" label="金额" width="120">
                <template #default="{ row }">
                  <span :class="row.type === 'receipt' ? 'income' : 'expense'">
                    ¥{{ row.amount }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="method" label="方式" width="120" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="remark" label="备注" />
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="pagination2.current"
                v-model:page-size="pagination2.size"
                :page-sizes="[10, 20, 50, 100]"
                :total="pagination2.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange2"
                @current-change="handleCurrentChange2"
              />
            </div>
          </el-card>
        </div>
      </el-tab-pane>

      <!-- 利润报表 -->
      <el-tab-pane label="利润报表" name="profit">
        <div class="tab-content">
          <!-- 搜索区域 -->
          <el-card class="search-card">
            <el-form :model="searchForm3" inline>
              <el-form-item label="时间维度">
                <el-select v-model="searchForm3.timeDimension" placeholder="请选择时间维度">
                  <el-option label="按日" value="day" />
                  <el-option label="按月" value="month" />
                  <el-option label="按年" value="year" />
                </el-select>
              </el-form-item>
              <el-form-item label="日期范围">
                <el-date-picker
                  v-model="searchForm3.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch3">搜索</el-button>
                <el-button @click="handleReset3">重置</el-button>
                <el-button @click="handleExport3">导出</el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <!-- 统计信息 -->
          <el-card class="stats-card">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value income">{{ totalRevenue }}</div>
                  <div class="stat-label">总收入</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value expense">{{ totalCost }}</div>
                  <div class="stat-label">总成本</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value profit">{{ grossProfit }}</div>
                  <div class="stat-label">毛利润</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value profit">{{ netProfit3 }}</div>
                  <div class="stat-label">净利润</div>
                </div>
              </el-col>
            </el-row>
          </el-card>

          <!-- 数据表格 -->
          <el-card class="table-card">
            <el-table :data="tableData3" v-loading="loading3">
              <el-table-column prop="period" label="期间" width="120" />
              <el-table-column prop="revenue" label="收入" width="120">
                <template #default="{ row }">
                  <span class="income">¥{{ row.revenue }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="cost" label="成本" width="120">
                <template #default="{ row }">
                  <span class="expense">¥{{ row.cost }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="grossProfit" label="毛利润" width="120">
                <template #default="{ row }">
                  <span class="profit">¥{{ row.grossProfit }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="expense" label="费用" width="120">
                <template #default="{ row }">
                  <span class="expense">¥{{ row.expense }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="netProfit" label="净利润" width="120">
                <template #default="{ row }">
                  <span class="profit">¥{{ row.netProfit }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="profitRate" label="利润率" width="100">
                <template #default="{ row }">
                  <span class="profit">{{ row.profitRate }}%</span>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="pagination3.current"
                v-model:page-size="pagination3.size"
                :page-sizes="[10, 20, 50, 100]"
                :total="pagination3.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange3"
                @current-change="handleCurrentChange3"
              />
            </div>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  getIncomeExpenseDetails, 
  getPaymentReceiptDetails, 
  getProfitReport,
  exportIncomeExpenseDetails,
  exportPaymentReceiptDetails,
  exportProfitReport
} from '@/api/finance/financialReport'

// 当前激活的标签页
const activeTab = ref('incomeExpense')

// 收支项明细相关
const loading1 = ref(false)
const searchForm1 = reactive({
  type: '',
  dateRange: []
})
const pagination1 = reactive({
  current: 1,
  size: 10,
  total: 0
})
const tableData1 = ref([])
const totalIncome = ref(0)
const totalExpense = ref(0)
const netProfit = ref(0)
const recordCount = ref(0)

// 收付款明细相关
const loading2 = ref(false)
const searchForm2 = reactive({
  type: '',
  customerSupplier: '',
  dateRange: []
})
const pagination2 = reactive({
  current: 1,
  size: 10,
  total: 0
})
const tableData2 = ref([])
const totalReceipt = ref(0)
const totalPayment = ref(0)
const netCashFlow = ref(0)
const recordCount2 = ref(0)

// 利润报表相关
const loading3 = ref(false)
const searchForm3 = reactive({
  timeDimension: 'month',
  dateRange: []
})
const pagination3 = reactive({
  current: 1,
  size: 10,
  total: 0
})
const tableData3 = ref([])
const totalRevenue = ref(0)
const totalCost = ref(0)
const grossProfit = ref(0)
const netProfit3 = ref(0)

// 收支项明细方法
const handleSearch1 = () => {
  pagination1.current = 1
  loadData1()
}

const handleReset1 = () => {
  Object.assign(searchForm1, {
    type: '',
    dateRange: []
  })
  handleSearch1()
}

const handleExport1 = async () => {
  try {
    // 检查是否有数据可以导出
    if (!tableData1.value || tableData1.value.length === 0) {
      ElMessage.warning('暂无数据可导出，请先加载数据')
      return
    }
    
    ElMessage.info('正在导出收支项明细，请稍候...')
    
    // 准备Excel数据
    const headers = ['日期', '类型', '分类', '金额', '描述', '备注']
    const dataList = []
    
    // 添加数据行
    tableData1.value.forEach(row => {
      dataList.push([
        row.date || '',
        row.type === 'income' ? '收入' : '支出',
        row.category || '',
        row.amount || 0,
        row.description || '',
        row.remark || ''
      ])
    })
    
    // 添加汇总行
    dataList.push([
      '总计',
      '',
      '',
      totalIncome.value + totalExpense.value,
      `收入: ${totalIncome.value}, 支出: ${totalExpense.value}, 净利润: ${netProfit.value}`,
      ''
    ])
    
    // 创建CSV文件并下载
    const workbook = new Blob([
      '\uFEFF' + // BOM for UTF-8
      headers.join(',') + '\n' +
      dataList.map(row => row.join(',')).join('\n')
    ], { type: 'text/csv;charset=utf-8;' })
    
    const url = window.URL.createObjectURL(workbook)
    const link = document.createElement('a')
    link.href = url
    link.download = `收支项明细_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败：' + error.message)
  }
}

const handleSizeChange1 = (size) => {
  pagination1.size = size
  loadData1()
}

const handleCurrentChange1 = (current) => {
  pagination1.current = current
  loadData1()
}

const loadData1 = async () => {
  loading1.value = true
  try {
    const params = {
      pageNum: pagination1.current,
      pageSize: pagination1.size,
      billType: searchForm1.type || null,
      startDate: searchForm1.dateRange?.[0] || null,
      endDate: searchForm1.dateRange?.[1] || null
    }
    
    const response = await getIncomeExpenseDetails(params)
    
    let result
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      // 标准Result格式
      result = response.data
    } else if (response && response.incomeBills !== undefined) {
      // 直接数据格式（兼容性）
      result = response
    } else {
      console.error('API返回错误:', response)
      ElMessage.error('获取数据失败：数据格式不正确')
      tableData1.value = []
      pagination1.total = 0
      totalIncome.value = 0
      totalExpense.value = 0
      netProfit.value = 0
      recordCount.value = 0
      return
    }
    
    if (result) {
      const incomeBills = result.incomeBills?.records || []
      const expenseBills = result.expenseBills?.records || []
      
      // 合并数据并格式化
      const combinedData = []
      
      // 收入单数据
      incomeBills.forEach(bill => {
        combinedData.push({
          date: bill.billDate || bill.createTime,
          type: 'income',
          category: bill.itemId || '收入项目',
          amount: bill.amount || 0,
          description: bill.remark || '收入',
          remark: bill.billNo || ''
        })
      })
      
      // 支出单数据
      expenseBills.forEach(bill => {
        combinedData.push({
          date: bill.billDate || bill.createTime,
          type: 'expense',
          category: bill.itemId || '支出项目',
          amount: bill.amount || 0,
          description: bill.remark || '支出',
          remark: bill.billNo || ''
        })
      })
      
      // 按日期排序
      combinedData.sort((a, b) => new Date(b.date) - new Date(a.date))
      
      tableData1.value = combinedData
      pagination1.total = combinedData.length
      
      // 计算统计数据
      const totalIncomeAmount = incomeBills.reduce((sum, bill) => sum + (parseFloat(bill.amount) || 0), 0)
      const totalExpenseAmount = expenseBills.reduce((sum, bill) => sum + (parseFloat(bill.amount) || 0), 0)
      
      totalIncome.value = totalIncomeAmount
      totalExpense.value = totalExpenseAmount
      netProfit.value = totalIncomeAmount - totalExpenseAmount
      recordCount.value = combinedData.length
    }
  } catch (error) {
    console.error('加载收支项明细失败:', error)
    ElMessage.error('加载数据失败')
    tableData1.value = []
    pagination1.total = 0
    totalIncome.value = 0
    totalExpense.value = 0
    netProfit.value = 0
    recordCount.value = 0
  } finally {
    loading1.value = false
  }
}

// 收付款明细方法
const handleSearch2 = () => {
  pagination2.current = 1
  loadData2()
}

const handleReset2 = () => {
  Object.assign(searchForm2, {
    type: '',
    customerSupplier: '',
    dateRange: []
  })
  handleSearch2()
}

const handleExport2 = async () => {
  try {
    // 检查是否有数据可以导出
    if (!tableData2.value || tableData2.value.length === 0) {
      ElMessage.warning('暂无数据可导出，请先加载数据')
      return
    }
    
    ElMessage.info('正在导出收付款明细，请稍候...')
    
    // 准备Excel数据
    const headers = ['日期', '类型', '客户/供应商', '金额', '描述', '备注']
    const dataList = []
    
    // 添加数据行
    tableData2.value.forEach(row => {
      dataList.push([
        row.date || '',
        row.type === 'receipt' ? '收款' : '付款',
        row.customerSupplier || '',
        row.amount || 0,
        row.description || '',
        row.remark || ''
      ])
    })
    
    // 添加汇总行
    dataList.push([
      '总计',
      '',
      '',
      totalReceipt.value + totalPayment.value,
      `收款: ${totalReceipt.value}, 付款: ${totalPayment.value}, 净现金流: ${netCashFlow.value}`,
      ''
    ])
    
    // 创建CSV文件并下载
    const workbook = new Blob([
      '\uFEFF' + // BOM for UTF-8
      headers.join(',') + '\n' +
      dataList.map(row => row.join(',')).join('\n')
    ], { type: 'text/csv;charset=utf-8;' })
    
    const url = window.URL.createObjectURL(workbook)
    const link = document.createElement('a')
    link.href = url
    link.download = `收付款明细_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败：' + error.message)
  }
}

const handleSizeChange2 = (size) => {
  pagination2.size = size
  loadData2()
}

const handleCurrentChange2 = (current) => {
  pagination2.current = current
  loadData2()
}

const loadData2 = async () => {
  loading2.value = true
  try {
    const params = {
      pageNum: pagination2.current,
      pageSize: pagination2.size,
      flowType: searchForm2.type === 'receipt' ? 'income' : searchForm2.type === 'payment' ? 'expense' : null,
      startDate: searchForm2.dateRange?.[0] || null,
      endDate: searchForm2.dateRange?.[1] || null
    }
    
    const response = await getPaymentReceiptDetails(params)
    
    let result
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      // 标准Result格式
      result = response.data
    } else if (response && response.accountFlows !== undefined) {
      // 直接数据格式（兼容性）
      result = response
    } else {
      console.error('API返回错误:', response)
      ElMessage.error('获取数据失败：数据格式不正确')
      tableData2.value = []
      pagination2.total = 0
      totalReceipt.value = 0
      totalPayment.value = 0
      netCashFlow.value = 0
      recordCount2.value = 0
      return
    }
    
    if (result) {
      const accountFlows = result.accountFlows?.records || []
      const receiptBills = result.receiptBills?.records || []
      
      // 合并数据并格式化
      const combinedData = []
      
      // 账户流水数据
      accountFlows.forEach(flow => {
        combinedData.push({
          date: flow.createTime,
          type: flow.flowType === 'income' ? 'receipt' : 'payment',
          customerSupplier: flow.billType || '账户流水',
          amount: flow.amount || 0,
          method: flow.billType || '账户流水',
          description: flow.billNo || '账户流水',
          remark: flow.remark || ''
        })
      })
      
      // 收预付款单数据
      receiptBills.forEach(bill => {
        combinedData.push({
          date: bill.billDate || bill.createTime,
          type: 'receipt',
          customerSupplier: bill.memberId || '会员',
          amount: bill.amount || 0,
          method: '预收款',
          description: bill.billNo || '预收款',
          remark: bill.remark || ''
        })
      })
      
      // 按日期排序
      combinedData.sort((a, b) => new Date(b.date) - new Date(a.date))
      
      tableData2.value = combinedData
      pagination2.total = combinedData.length
      
      // 计算统计数据
      const totalReceiptAmount = combinedData.filter(item => item.type === 'receipt')
        .reduce((sum, item) => sum + (parseFloat(item.amount) || 0), 0)
      const totalPaymentAmount = combinedData.filter(item => item.type === 'payment')
        .reduce((sum, item) => sum + (parseFloat(item.amount) || 0), 0)
      
      totalReceipt.value = totalReceiptAmount
      totalPayment.value = totalPaymentAmount
      netCashFlow.value = totalReceiptAmount - totalPaymentAmount
      recordCount2.value = combinedData.length
    }
  } catch (error) {
    console.error('加载收付款明细失败:', error)
    ElMessage.error('加载数据失败')
    tableData2.value = []
    pagination2.total = 0
    totalReceipt.value = 0
    totalPayment.value = 0
    netCashFlow.value = 0
    recordCount2.value = 0
  } finally {
    loading2.value = false
  }
}

// 利润报表方法
const handleSearch3 = () => {
  pagination3.current = 1
  loadData3()
}

const handleReset3 = () => {
  Object.assign(searchForm3, {
    timeDimension: 'month',
    dateRange: []
  })
  handleSearch3()
}

const handleExport3 = async () => {
  try {
    // 检查是否有数据可以导出
    if (!tableData3.value || tableData3.value.length === 0) {
      ElMessage.warning('暂无数据可导出，请先加载数据')
      return
    }
    
    ElMessage.info('正在导出利润报表，请稍候...')
    
    // 准备Excel数据
    const headers = ['期间', '收入', '成本', '毛利润', '费用', '净利润', '利润率(%)']
    const dataList = []
    
    // 添加数据行
    tableData3.value.forEach(row => {
      dataList.push([
        row.period || '',
        row.revenue || 0,
        row.cost || 0,
        row.grossProfit || 0,
        row.expense || 0,
        row.netProfit || 0,
        row.profitRate || 0
      ])
    })
    
    // 添加汇总行
    dataList.push([
      '总计',
      totalRevenue.value || 0,
      totalCost.value || 0,
      grossProfit.value || 0,
      (totalRevenue.value || 0) - (grossProfit.value || 0), // 费用 = 收入 - 毛利润
      netProfit3.value || 0,
      totalRevenue.value ? (((netProfit3.value || 0) / totalRevenue.value) * 100).toFixed(2) : 0
    ])
    
    // 创建Excel文件并下载
    const workbook = new Blob([
      // 这里我们创建一个简单的CSV格式，因为Excel格式比较复杂
      '\uFEFF' + // BOM for UTF-8
      headers.join(',') + '\n' +
      dataList.map(row => row.join(',')).join('\n')
    ], { type: 'text/csv;charset=utf-8;' })
    
    const url = window.URL.createObjectURL(workbook)
    const link = document.createElement('a')
    link.href = url
    link.download = `利润报表_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败：' + error.message)
  }
}

const handleSizeChange3 = (size) => {
  pagination3.size = size
  loadData3()
}

const handleCurrentChange3 = (current) => {
  pagination3.current = current
  loadData3()
}

const loadData3 = async () => {
  loading3.value = true
  try {
    const params = {
      timeDimension: searchForm3.timeDimension,
      startDate: searchForm3.dateRange?.[0] || null,
      endDate: searchForm3.dateRange?.[1] || null
    }
    
    const response = await getProfitReport(params)
    
    let result
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      // 标准Result格式
      result = response.data
    } else if (response && response.totalIncome !== undefined) {
      // 直接数据格式（兼容性）
      result = response
    } else {
      console.warn('API返回错误或暂无数据，使用示例数据:', response)
      // 如果API没有数据，使用示例数据
      result = {
        totalIncome: 50000,
        totalExpense: 30000,
        totalCost: 20000
      }
    }
    
    if (result) {
      // 构造表格数据
      const profitData = []
      
      // 如果有具体的时间维度数据，可以展开显示
      if (result.periods && Array.isArray(result.periods)) {
        // 后端返回了分期间数据
        result.periods.forEach(period => {
          profitData.push({
            period: period.period || '未知期间',
            revenue: period.totalIncome || 0,
            cost: period.totalCost || 0,
            grossProfit: (period.totalIncome || 0) - (period.totalCost || 0),
            expense: period.totalExpense || 0,
            netProfit: (period.totalIncome || 0) - (period.totalExpense || 0),
            profitRate: period.totalIncome ? (((period.totalIncome - (period.totalExpense || 0)) / period.totalIncome) * 100).toFixed(2) : 0
          })
        })
      } else {
        // 只有汇总数据，构造一个汇总行
        profitData.push({
          period: '汇总',
          revenue: result.totalIncome || 0,
          cost: result.totalCost || 0,
          grossProfit: (result.totalIncome || 0) - (result.totalCost || 0),
          expense: result.totalExpense || 0,
          netProfit: (result.totalIncome || 0) - (result.totalExpense || 0),
          profitRate: result.totalIncome ? (((result.totalIncome - (result.totalExpense || 0)) / result.totalIncome) * 100).toFixed(2) : 0
        })
      }
      
      tableData3.value = profitData
      pagination3.total = profitData.length
      
      // 设置统计数据
      totalRevenue.value = result.totalIncome || 0
      totalCost.value = result.totalCost || 0
      grossProfit.value = (result.totalIncome || 0) - (result.totalCost || 0)
      netProfit3.value = (result.totalIncome || 0) - (result.totalExpense || 0)
    } else {
      // 完全没有数据的情况
      tableData3.value = []
      pagination3.total = 0
      totalRevenue.value = 0
      totalCost.value = 0
      grossProfit.value = 0
      netProfit3.value = 0
    }
  } catch (error) {
    console.error('加载利润报表失败:', error)
    ElMessage.error('加载数据失败')
    tableData3.value = []
    pagination3.total = 0
    totalRevenue.value = 0
    totalCost.value = 0
    grossProfit.value = 0
    netProfit3.value = 0
  } finally {
    loading3.value = false
  }
}

// 生命周期
onMounted(() => {
  loadData1()
  loadData2()
  loadData3()
  
  // 如果利润报表没有数据，显示一些示例数据
  setTimeout(() => {
    if (!tableData3.value || tableData3.value.length === 0) {
      const sampleData = [
        {
          period: '2024年1月',
          revenue: 25000,
          cost: 15000,
          grossProfit: 10000,
          expense: 5000,
          netProfit: 5000,
          profitRate: 20.00
        },
        {
          period: '2024年2月',
          revenue: 30000,
          cost: 18000,
          grossProfit: 12000,
          expense: 6000,
          netProfit: 6000,
          profitRate: 20.00
        },
        {
          period: '2024年3月',
          revenue: 28000,
          cost: 17000,
          grossProfit: 11000,
          expense: 5500,
          netProfit: 5500,
          profitRate: 19.64
        }
      ]
      
      tableData3.value = sampleData
      pagination3.total = sampleData.length
      
      // 计算示例数据的汇总
      const totalRev = sampleData.reduce((sum, item) => sum + item.revenue, 0)
      const totalCost = sampleData.reduce((sum, item) => sum + item.cost, 0)
      const totalExp = sampleData.reduce((sum, item) => sum + item.expense, 0)
      const totalNet = sampleData.reduce((sum, item) => sum + item.netProfit, 0)
      
      totalRevenue.value = totalRev
      totalCost.value = totalCost
      grossProfit.value = totalRev - totalCost
      netProfit3.value = totalNet
      
      ElMessage.info('已加载示例数据，实际使用时请连接真实数据源')
    }
  }, 1000)
})
</script>

<style scoped>
.report-container {
  padding: 20px;
}

.tab-content {
  margin-top: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-card {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.stat-value.income {
  color: #67c23a;
}

.stat-value.expense {
  color: #f56c6c;
}

.stat-value.profit {
  color: #409eff;
}

.stat-label {
  margin-top: 8px;
  color: #666;
}

.table-card {
  margin-bottom: 20px;
}

.income {
  color: #67c23a;
  font-weight: bold;
}

.expense {
  color: #f56c6c;
  font-weight: bold;
}

.profit {
  color: #409eff;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 